package com.powernobug.util;

import com.powernobug.bean.model.MarketStorage;
import lombok.Builder;

import javax.servlet.http.Part;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class FileUtil {
    private FileUtil() {}

    public static String generateUUIDName(String fileName) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String uploadDate = sdf.format(new Date());
        String uuid = UUID.randomUUID().toString();
        StringBuffer reverse = new StringBuffer(uuid.substring(uuid.lastIndexOf("-") - 4)).reverse().insert(0, uploadDate);
        return reverse + suffix;
    }

    public static MarketStorage pictureDataPack(Part picture, String requestRootAddress, String picPath) {
        String submittedFileName = picture.getSubmittedFileName();
        String uuidName = generateUUIDName(submittedFileName);
        String contentType = picture.getContentType();
        Integer fileSize = (int) picture.getSize();
        String fileURL = requestRootAddress + picPath.substring(picPath.indexOf(":")+1) + "/" + uuidName;
        Date addTime = new Date();
        Date uploadDate = new Date();
        return MarketStorage.builder()
                .key(uuidName)
                .name(submittedFileName)
                .type(contentType)
                .size(fileSize)
                .url(fileURL)
                .addTime(addTime)
                .updateTime(uploadDate)
                .deleted(false)
                .build();
    }
}
